package com.wjx.collect;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileWriter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static java.lang.Thread.sleep;

/**
 * @Description
 * @Author zouping
 * @Date 2025/1/14 10:09
 */
public class Http {
    private static final Logger logger = LoggerFactory.getLogger(Collect.class);
    private static int currentPrefix = 60;
    private static int currentIndex = 1;
    private static final int TOTAL_RECORDS = 230;
    private static final String WJX_URL = "https://wcsmsurvey.wjx.com/resultquery.aspx?activity=298775450";
    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException {
        Http http = new Http();
        http.collectData();
//        FormBody formBody = buildQueryParams(3102, 81);
//        String response = sendRequest(formBody);
//        log.info("Response: " + response);
    }

    private void collectData() throws InterruptedException {
        for (; currentIndex <= TOTAL_RECORDS; currentIndex++) {
            boolean found = false;
            for (; currentPrefix <= 9999; currentPrefix++) {
                FormBody formBody = buildQueryParams(currentPrefix, currentIndex);
                String response = sendRequest(formBody);
                sleep(500);
                if (response == null) {
                    // 出现意外
                    logger.error("出现意外 ID: " + String.format("%04d", currentPrefix) + String.format("%04d", currentIndex));
                } else if (response != null && response.contains("没有查询到结果，请确认所填信息正确无误！")) {
                    // 确定没有查询到结果
                    logger.info("确定无结果 ID: " + String.format("%04d", currentPrefix) + String.format("%04d", currentIndex));
                } else if (response != null && response.contains("期末机考满分100分，折算40分，期末机考为服务器自动核算成绩导出")) {
                    // 确定查询到结果
                    logger.info("确定有结果 ID: " + String.format("%04d", currentPrefix) + String.format("%04d", currentIndex));
                    saveToFile(String.format("%04d", currentPrefix) + String.format("%04d", currentIndex), response);
                    found = true;
                }
            }
            if (!found) {
                logger.error("Failed to find data for student ID: " + currentIndex);
            }
        }
    }


    private static String sendRequest(FormBody queryParams) {
        String r = null;
        String ip = generateRandomIP();
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, 443));
        Request request = new Request.Builder()
                .url(WJX_URL)
                .post(queryParams)
                .addHeader("X-Forwarded-For", ip)
                .addHeader("Content-Type", "text/html; charset=utf-8")
                .addHeader("Transfer-Encoding", "chunked")
//                .addHeader("Accept-encoding", "gzip")
//                .addHeader("Accept-language", "zh-CN,zh;q=0.9")
                .addHeader("Content-type", "application/x-www-form-urlencoded")
                .addHeader("Cookie", ".ASPXANONYMOUS=6CUdvrmc2wEkAAAAZDA1MWQ4MjAtZDU4Yi00ZGMzLThiYjQtYThkODU1ZmYwOTZluIkcbzJeK01vxDT9_yYydvCe-z41; _uab_collina=173682487538558519256951; acw_tc=1a0c579a17368327449963873e0047a26716ddd89e01659ac074dbfc78e503; acw_sc__v2=6785f6e84d12e9032170b06100305c66aa2accbd; tfstk=gIMxFXfuPUYcOw8puxRujPHPR6tkZQm2eqoCIP4c143-AVW0irq011gnD5_msOc8W4g8lsmM_h3t5qo0ScO45ci4h5l0Sr4TBcupqevHKmo4QWTH-pXrwo5bLN_b5NV7PkeTcMzBq5m4QRTu5GZ7omuBpamx1Rt8FlETfRN_l3e7Yz6bftw_P3UzfRZb5l9SVorgfZaj50t8bza_CRg_FbFWWzsbSOhLrDIJsCeGCOM8D7OoczN_6hqbMyibyeTIedNYRmaRCeWfWl4TzvTkw0uKGqqrWpL8Q4ls5l35PFVqfb38DqYd7PDqmAUmDITq28zYFxGdfOi8HrPth7bvyyMqVvy7ZptKVYum0YnGfdZo-ziqhRpBY-ebl8ErIUWbWbGsnSyNleVqfb38DJsy9vDL95_3JlfX23CN_SZrgo2KWmO0Dgr8-npO_1Py4uUH23CN_SZz2yxvk15aa35..; querycond298775450=30000%7C31020081; ssxmod_itna=iqGx2DuDBC0=qiKGHiGdmSnniDkWYYi33KDgAip8D0vxi=bDSxGKidDqxBmmZDqP4izrBcdFerYgee4UY00pEIjS7AqdveAQx0aDbqGk+43xiiSDCeDIDWeDiDG+tDFxYoDeOyQDFzHNXZzd=D3qDwDB=DmqG2Yl=Dm4DfDDLyiGGtYit4DDN4DaAmDYpy0MdPomrDAqxlQ0GyD0tDIqGXz29=xDUkupDV0ua75ppnierDtqD9znU07j4gDWNuKp+x7x+xm7LrmBAeQixT30qUhAwKB7G=QiwKeVPP9IkqSzEUxDfhA7oxD=; ssxmod_itna2=iqGx2DuDBC0=qiKGHiGdmSnniDkWYYi33KDgAiEDn93bqDsKiDc7Dj4SZdQ2/=o7nUxAPeMQYjYm1eWbCDb7r=zk0D75oRQmjpM+gq5=ve=1qbvI0QRml8+n79gY+R10r5z5snWYP3UB3E6eq5eYCAqonGAWqr9GGEKhq4CQB2RACKD1lKq0WEPpx5serKIG4EaD7QidrKsQhIAK7hN=DFiuhFLUpeDFqD2YiD==")
                .build();
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .proxy(proxy)
                .connectTimeout(5L, TimeUnit.SECONDS)
                .readTimeout(30L, TimeUnit.SECONDS)
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            r = new String(response.body().bytes(),"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return r;
    }

    private static String generateRandomIP() {
        Random random = new Random();
        return random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256);
    }

    private static FormBody buildQueryParams(int prefix, int studentId) {
        FormBody formBody = new FormBody.Builder()
                .add("__VIEWSTATE", "/wEPDwUKMTA3MTcwNjU3MGRkp/PbT1HrijCO9lgIvBe1t4rVLX4=")
                .add("__VIEWSTATEGENERATOR", "A51944F2")
                .add("__EVENTVALIDATION", "/wEdAAR8yOtO1hCAFfVUxF3LpttsfxLSikTZqx6XzQUk71djD7A88eHGsukWIJIFOXmn8igR0tAd5ZA4PMHE5c0EdNu892bSB+W1KBnyz2tC8tH1UxF66uI=")
                .add("hfPostType", "1")
                .add("hfQuery", "30000|" + String.format("%04d", prefix) + String.format("%04d", studentId))
                .add("hfUserName", "")
                .build();
        return formBody;
    }

    private void saveToFile(String id, String response) {
        try (FileWriter writer = new FileWriter(id + ".txt")) {
            writer.write("Response: " + response);
        } catch (IOException e) {
            logger.error("Exception occurred while saving data to file", e);
        }
    }
}
